<template>
  <div class="organizations-management">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">组织管理</h2>
        <div class="status-badges">
          <el-tag type="success" effect="dark">
            <el-icon><OfficeBuilding /></el-icon>
            总组织数: {{ stats.total }}
          </el-tag>
          <el-tag type="primary" effect="dark">
            <el-icon><Check /></el-icon>
            启用组织: {{ stats.active }}
          </el-tag>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleShowAddOrganization">
          <el-icon><Plus /></el-icon>
          新增组织
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤区 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" label-width="80px" inline>
        <el-form-item label="组织名称">
          <el-input 
            v-model="queryParams.name" 
            placeholder="请输入组织名称" 
            clearable
            @keyup.enter="loadOrganizations"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadOrganizations">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleResetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 组织列表 -->
    <el-card class="table-card" shadow="never" v-loading="loading">
      <template #header>
        <div class="table-header">
          <div class="table-title">
            <el-icon><OfficeBuilding /></el-icon>
            <span>组织列表</span>
          </div>
          <div class="table-actions">
            <el-button-group>
              <el-button 
                :icon="View" 
                @click="handleViewOrganization"
                :disabled="!selectedOrganization"
              >
                查看详情
              </el-button>
              <el-button 
                :icon="Edit" 
                @click="handleEditOrganization"
                :disabled="!selectedOrganization"
              >
                编辑
              </el-button>
              <el-button 
                :icon="Delete" 
                type="danger"
                @click="handleDeleteOrganization"
                :disabled="!selectedOrganization"
              >
                删除
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <el-table
        :data="tableData"
        ref="organizationTableRef"
        highlight-current-row
        @current-change="handleCurrentChange"
        @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="组织名称" min-width="200">
          <template #default="{ row }">
            <strong>{{ row.name }}</strong>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="组织编码" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click.stop="handleEditOrganization(row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="info" 
              @click.stop="handleViewUsers(row)"
            >
              成员管理
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click.stop="handleDeleteOrganization(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 组织表单对话框 -->
    <OrganizationFormDialog
      v-model="showOrganizationFormDialog"
      :form-mode="formMode"
      :organization-data="currentOrganization"
      @submit="handleSaveOrganization"
      @close="handleCloseOrganizationFormDialog"
    />

    <!-- 用户管理抽屉 -->
    <UserManagementDrawer
      v-model="showUserManagementDrawer"
      :organization="selectedOrganization"
      @refresh="loadOrganizations"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  OfficeBuilding, Plus, Refresh, Search, View, Edit, Delete, Check
} from '@element-plus/icons-vue'

// 组件导入
import OrganizationFormDialog from './components/OrganizationFormDialog.vue'
import UserManagementDrawer from './components/UserManagementDrawer.vue'

// 导入API函数
import { organizationAPI } from '@/api/organization'

// 响应式数据
const organizationTableRef = ref()
const loading = ref(false)

const selectedOrganization = ref<any>(null)
const tableData = ref<any[]>([])
const total = ref(0)

// 表单相关状态
const showOrganizationFormDialog = ref(false)
const formMode = ref<'create' | 'edit'>('create')
const currentOrganization = ref<any>(null)
const showUserManagementDrawer = ref(false)

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 20,
  name: '',
  status: undefined
})

// 统计信息
const stats = reactive({
  total: 0,
  active: 0
})

// 方法
const loadOrganizations = async () => {
  loading.value = true
  try {
    // 调用API获取组织列表
    const response: any = await organizationAPI.getOrganizations(queryParams)
    tableData.value = response.data.list
    total.value = response.data.pagination.total
    
    // 更新统计信息
    stats.total = response.data.pagination.total
    stats.active = response.data.list.filter((item: any) => item.status === 1).length
  } catch (error) {
    console.error('加载组织列表失败:', error)
    ElMessage.error('加载组织列表失败')
  } finally {
    loading.value = false
  }
}

const handleShowAddOrganization = () => {
  formMode.value = 'create'
  currentOrganization.value = null
  showOrganizationFormDialog.value = true
}

const handleEditOrganization = (organization: any) => {
  formMode.value = 'edit'
  currentOrganization.value = organization
  showOrganizationFormDialog.value = true
}

const handleViewOrganization = () => {
  if (selectedOrganization.value) {
    handleEditOrganization(selectedOrganization.value)
  }
}

const handleDeleteOrganization = async (organization: any) => {
  const org = organization || selectedOrganization.value
  if (!org) {
    ElMessage.warning('请选择要删除的组织')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除组织 "${org.name}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )

    await organizationAPI.deleteOrganization(org.id)
    ElMessage.success('组织删除成功')
    await loadOrganizations()
    
    // 清空选择
    selectedOrganization.value = null
    if (organizationTableRef.value) {
      organizationTableRef.value.setCurrentRow()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除组织失败:', error)
      ElMessage.error('删除组织失败: ' + (error as Error).message)
    }
  }
}

const handleViewUsers = (organization: any) => {
  selectedOrganization.value = organization
  showUserManagementDrawer.value = true
}

const handleSaveOrganization = async () => {
  await loadOrganizations()
}

const handleCloseOrganizationFormDialog = () => {
  showOrganizationFormDialog.value = false
  currentOrganization.value = null
}

const handleRefresh = () => {
  loadOrganizations()
}

const handleResetFilters = () => {
  queryParams.name = ''
  queryParams.status = undefined
  loadOrganizations()
}

const handleCurrentChange = (organization: any) => {
  selectedOrganization.value = organization
}

const handleRowClick = (row: any) => {
  selectedOrganization.value = row
  organizationTableRef.value.setCurrentRow(row)
}

const handleSizeChange = (val: number) => {
  queryParams.limit = val
  loadOrganizations()
}

const handleCurrentChangePage = (val: number) => {
  queryParams.page = val
  loadOrganizations()
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  loadOrganizations()
})
</script>

<style scoped>
.organizations-management {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
  min-height: 100vh;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .header-left {
      .page-title {
        margin: 0 0 12px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2d3d;
      }
      
      .status-badges {
        display: flex;
        gap: 12px;
        
        .el-tag {
          display: flex;
          align-items: center;
          gap: 4px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
      
      .el-button {
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        &:active {
          transform: translateY(0);
        }
      }
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }
  }
  
  .table-card {
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }
    
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .table-actions {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-button-group {
        .el-button {
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 20px 0;
  }
  
  /* 移动端适配 */
  @media (max-width: 767px) {
    .organizations-management {
      padding: 12px;
    }
    
    .page-header {
      flex-direction: column;
      gap: 16px;
      
      .header-left {
        .page-title {
          font-size: 20px;
        }
        
        .status-badges {
          flex-wrap: wrap;
        }
      }
      
      .header-actions {
        width: 100%;
        flex-wrap: wrap;
        
        .el-button {
          flex: 1;
          min-width: 80px;
        }
      }
    }
    
    .filter-card {
      .el-form {
        .el-form-item {
          width: 100%;
          margin-right: 0;
        }
      }
    }
  }
}
</style>